import 'package:boss/main.dart';
import 'package:boss/models/reback_order_list_data.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:async/async.dart';

class AfterSaleListProvider extends ChangeNotifier {
  DateTime startTime = DateUtils.startOfTheDay(DateTime.now());

  String get startTimeText {
    if (startTime == null) {
      return null;
    }

    return flustars.DateUtil.formatDate(startTime, format: flustars.DateFormats.y_mo_d);
  }

  String keyword = '';

  List<RebackOrderItem> orders = [];

  GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  Future<Result<List<RebackOrderItem>>> queryTakeOutRefundOrderList(int page) async {
    try {
      var res = await api.queryTakeOutRefundOrderList(
        startTime: startTimeText,
        page: page,
        input: keyword,
      );
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      return Result.value(res.data.items);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  Future<Result<List<RebackOrderItem>>> refreshData() async {
    var takeoutOrders = await queryTakeOutRefundOrderList(1);

    if (takeoutOrders.isError) {
      return takeoutOrders;
    }

    this.orders = takeoutOrders.asValue.value;
    notifyListeners();

    return Result.value(takeoutOrders.asValue.value);
  }

  Future<Result<List<RebackOrderItem>>> loadData() async {
    var page = orders.length ~/ 10 + 1;
    var takeoutOrders = await queryTakeOutRefundOrderList(page);

    if (takeoutOrders.isError) {
      return takeoutOrders;
    }

    this.orders.addAll(takeoutOrders.asValue.value);
    notifyListeners();

    return Result.value(takeoutOrders.asValue.value);
  }
}
